package com.seek.educenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seek.commonutils.JwtUtils;
import com.seek.commonutils.MD5;
import com.seek.commonutils.ResponseResult;
import com.seek.commonutils.Statistics;
import com.seek.educenter.entity.UcenterMember;
import com.seek.educenter.entity.vo.RegisterVo;
import com.seek.educenter.mapper.UcenterMemberMapper;
import com.seek.educenter.service.UcenterMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seek.servicebase.exceptionhandler.SeekException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author wml
 * @since 2022-02-19
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 登录（账号密码）
    @Override
    public String loginUsername(String username, String password) {
        // 用户名和密码非空判断
        if (username == null || username.equals("") || password == null || password.equals("")) {
            throw new SeekException(20001, "登录失败，请检查用户名或密码是否输入正确。");
        }
        // 根据用户名查询对象
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UcenterMember member = baseMapper.selectOne(queryWrapper);
        // 判断查询对象是否为空
        if (member == null) {
            throw new SeekException(20001, "登录失败，输入的用户名不存在。");
        }
        // 判断密码
        if (!MD5.encrypt(password).equals(member.getPassword())) {
            throw new SeekException(20001, "登录失败，用户名或密码输入错误，请检查后重试。");
        }
        // 判断用户是否禁用
        if (member.getIsDisabled()) {
            throw new SeekException(20001, "登录失败，该用户已被禁用。");
        }
        // 登录成功，使用 jwt 工具，生成 token 字符串
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        return jwtToken;
    }

    // 登录（手机号验证码）
    @Override
    public String loginMobile(String phone, String code) {
        // 用户名和密码非空判断
        if (phone == null || phone.equals("") || code == null || code.equals("")) {
            throw new SeekException(20001, "登录失败，请检查手机号或验证码是否输入正确。");
        }
        // 根据用户名查询对象
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phone);
        UcenterMember member = baseMapper.selectOne(queryWrapper);
        // 判断查询对象是否为空
        if (member == null) {
            throw new SeekException(20001, "登录失败，输入的手机号不存在。");
        }
        // 判断验证码
        String redisCode = redisTemplate.opsForValue().get("login-" + phone);
        if (redisCode == null || redisCode.equals("")) {
            throw new SeekException(20001, "登录失败，验证码已失效，请重新发送验证码后重试。");
        }
        if (!code.equals(redisCode)) {
            throw new SeekException(20001, "登录失败，验证码输入错误，请检查后重试。");
        }
        // 判断用户是否禁用
        if (member.getIsDisabled()) {
            throw new SeekException(20001, "登录失败，该用户已被禁用。");
        }
        // 登录成功，使用 jwt 工具，生成 token 字符串
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        return jwtToken;
    }

    // 注册
    @Override
    public ResponseResult register(RegisterVo registerVo) {
        // 获取注册数据
        String username = registerVo.getUsername(); // 用户名
        String password = registerVo.getPassword(); // 密码
        String mobile = registerVo.getMobile(); // 手机号
        String code = registerVo.getVerificationCode(); // 验证码
        if (username == null || username.equals("")) {
            return ResponseResult.error().message("请输入用户名。");
        }
        if (password == null || password.equals("")) {
            return ResponseResult.error().message("请输入密码。");
        }
        if (mobile == null || mobile.equals("")) {
            return ResponseResult.error().message("请输入手机号。");
        }
        if (code == null || code.equals("")) {
            return ResponseResult.error().message("请输入验证码。");
        }
        // 判断验证码
        String redisCode = redisTemplate.opsForValue().get("register-" + mobile);
        if (redisCode == null || redisCode.equals("")) {
            return ResponseResult.error().message("验证码已失效，请重新发送验证码后重试。");
        }
        if (!code.equals(redisCode)) {
            return ResponseResult.error().message("验证码输入错误，请检查后重试。");
        }

        // 判断用户名是否重复，表里面存在相同的用户名不进行添加
        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Integer countUsername = baseMapper.selectCount(queryWrapper);
        if (countUsername == 1) {
            return ResponseResult.error().message("用户名已存在。");
        }
        // 判断手机号是否重复，表里面存在相同的手机号不进行添加
        queryWrapper.clear();
        queryWrapper.eq("mobile", mobile);
        Integer countMobile = baseMapper.selectCount(queryWrapper);
        if (countMobile == 1) {
            return ResponseResult.error().message("手机号已存在。");
        }
        // 将传过来的值添加到数据库
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setUsername(username);
        ucenterMember.setPassword(MD5.encrypt(password));
        ucenterMember.setMobile(mobile);
        ucenterMember.setNickname(username);
        ucenterMember.setAvatar("https://seek-20220113.oss-cn-beijing.aliyuncs.com/default/logo.gif");
        baseMapper.insert(ucenterMember);
        return ResponseResult.ok();
    }

    // 查询某一天注册人数
    @Override
    public Integer countRegisterByDate(String date) {
        return baseMapper.countRegisterByDate(date);
    }

    // 统计一个月以内注册的人数，按天数统计
    @Override
    public Map<String, Object> getRegistryMonth() {
        List<Statistics> list = baseMapper.getRegistryMonth();
        Map<String, Object> map = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        List<Integer> series = new ArrayList<>();
        for (Statistics statistics : list) {
            xAxis.add(statistics.getXAxis());
            series.add(statistics.getSeries());
        }
        map.put("xAxis", xAxis);
        map.put("series", series);
        return map;
    }

    // 统计一年内注册的人数，按月数统计
    @Override
    public Map<String, Object> getRegistryYear() {
        List<Statistics> list = baseMapper.getRegistryYear();
        Map<String, Object> map = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        List<Integer> series = new ArrayList<>();
        for (Statistics statistics : list) {
            xAxis.add(statistics.getXAxis());
            series.add(statistics.getSeries());
        }
        map.put("xAxis", xAxis);
        map.put("series", series);
        return map;
    }
}
